package com.shaolei.server;
import java.io.OutputStream;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import com.shaolei.basic.BASIC_QQ;
import com.shaolei.server_thread.Server_in;
import com.shaolei.server_thread.Server_out;

public class TCPEchoServer extends BASIC_QQ{
	private static ArrayList<String> active_client= new ArrayList<String>();
	private static HashMap<String, OutputStream> map_out= new HashMap<String, OutputStream>();
	private static HashMap<String, Socket> map_socket= new HashMap<String, Socket>();
	public static void main(String [] args) throws Exception{
		ServerSocket servSock=new ServerSocket(new TCPEchoServer().get_servPort());
		int clientid=1;// initial client id
		active_client.add("$$LIST");// FORMAT: {"LIST",{:clientid1},{:clientid2}...}
		//thread write for all users
		Server_out write1= new Server_out();
		Thread write= new Thread(write1);
		write.start();
		while(true){
			Socket clntSock=servSock.accept();
			InputStream in = clntSock.getInputStream();
			OutputStream out = clntSock.getOutputStream();
			SocketAddress clientAddress=clntSock.getRemoteSocketAddress();
			System.out.println("Handling client at "+clientAddress);
			
			//create read thread for new accepted client 
			Server_in read1= new Server_in(in, Integer.toString(clientid));
			Thread read= new Thread(read1);
			read.start();
			map_out.put(Integer.toString(clientid), out);
			map_socket.put(Integer.toString(clientid), clntSock);
			
			//add clientid to myQ
			String[] info_array={Integer.toString(clientid),"$$ID&&"+Integer.toString(clientid)};
			new Server_out().add2myQ(info_array);
			
			//add client id to active_client list
			active_client.add("&&"+Integer.toString(clientid));
			
			clientid++;
		}
	}
	public ArrayList<String> get_active_client(){
		return active_client;
	}
	public HashMap<String, OutputStream> get_map_out(){
		return map_out;
	}
	public HashMap<String, Socket> get_map_socket(){
		return map_socket;
	}
}